package main

import (
	"dcs/controller"
	"dcs/dcslog"
	"dcs/modbus"
	"dcs/upload"
	"fmt"
	"net"
	"net/http"
	"os"
)

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "DCS go version.")
}

func main() {

	modbus_port := "50200"

	// 获取命令行参数
	fmt.Println("命令行参数数量:", len(os.Args))
	for k, v := range os.Args {
		fmt.Printf("args[%v]=[%v]\n", k, v)

		// -p50000
		if v[:2] == "-p" {
			modbus_port = v[2:]
		}
	}

	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("/web"))))

	http.HandleFunc("/", handler)
	http.HandleFunc("/dcs/machines", controller.GetMachines)
	http.HandleFunc("/dcs/company", controller.GetCompanyInfo)

	fmt.Println("=== ListenAndServe 8080 ===")
	dcslog.Logger.Println("=== ListenAndServe 8080 ===")

	go http.ListenAndServe(":8080", nil)

	server, err := net.Listen("tcp", "0.0.0.0:"+modbus_port)
	if err != nil {
		panic(err)
	}
	defer server.Close()

	// 启动上传 新机台数据 的goroutine
	go upload.Cron_upload_base_machine()
	// 启动上传 机台状态数据 的goroutine
	go upload.Cron_upload_machine_status()

	for {
		conn, err := server.Accept()
		if err != nil {
			continue
		}
		client := modbus.Client{conn}
		go client.HandleModbusConn()
	}
}
